﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SJ.Platform.Extend.IOC.CurrentUser;
using SJ.Platform.Common;
using SJ.Platform.EFCore.Model;
using SJ.Platform.EFCore.Model.MenuManager;
using SJ.Platform.Extend.Request;
using SJ.Platform.Extend.Response;
using SJ.Platform.Extend.ModelExtend;
using SJ.Platform.EFCore.Model.AuthorityManager;
using Microsoft.EntityFrameworkCore;
using SJ.Platform.EFCore.DBOperation.DBOperation.MySQL.Sys;
using SJ.Platform.EFCore.Common;

namespace SJ.Platform.Api.Controllers.MenuManager
{
    /// <summary>
    /// 菜单操作接口
    /// </summary>
    [Route(GlobalVariableHandle.Scope_Api + "/Menu")]
    [ApiController]
    [Authorize(GlobalVariableHandle.Scope_Api)]
    public class MenuManagerController : ControllerBase
    {
        private readonly SJDBContext _context;
        private readonly Sys_MenuHandle sys_MenuHandle;
        private readonly Sys_AuthorityHandle sys_AuthorityHandle;
        private readonly ICurrentUser _currentUser;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContext">数据库</param>
        /// <param name="currentUser">当前用户</param>
        public MenuManagerController(SJDBContext dbContext, ICurrentUser currentUser)
        {
            _context = dbContext;
            sys_MenuHandle = new Sys_MenuHandle(dbContext);
            sys_AuthorityHandle = new Sys_AuthorityHandle(dbContext);
            _currentUser = currentUser;
        }

        /// <summary>
        /// 新增菜单
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("CreateMenuAsync")]
        public async Task<IActionResult> CreateMenuAsync([FromBody] SysMenu model)
        {
            try
            {
                bool result = await TransactionHandle.ExecuteInTransactionAsync<bool>(_context, async () =>
                {
                    var Menu = new SysMenu
                    {
                        Id = Guid.NewGuid().ToString(),
                        MenuName = model.MenuName,
                        Pid = model.Pid,
                        Url = model.Url,
                        Sort = model.Sort,
                        AddTime = DateTime.Now,
                        AddUserId = _currentUser.UserId,
                        EditTime = DateTime.Now,
                        EditUserId = _currentUser.UserId
                    };
                    var Authority = new SysAuthority
                    {
                        Id = Guid.NewGuid().ToString(),
                        AuthorityName = model.MenuName,
                        Pid = "",
                        AuthorityType = 1,
                        MenuId = Menu.Id,
                        AddTime = DateTime.Now,
                        AddUserId = _currentUser.UserId,
                        EditTime = DateTime.Now,
                        EditUserId = _currentUser.UserId
                    };
                    return await sys_MenuHandle.CreateAsync(Menu) && await sys_AuthorityHandle.CreateAsync(Authority);
                });

                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "菜单添加" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "菜单添加失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 修改菜单
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("UpdateMenuAsync")]
        public async Task<IActionResult> UpdateMenuAsync([FromBody] SysMenu model)
        {
            var Menu = new SysMenu
            {
                Id = model.Id,
                MenuName = model.MenuName,
                Pid = model.Pid,
                Url = model.Url,
                Sort = model.Sort,
                AddTime = DateTime.Now,
                AddUserId = model.AddUserId,
                EditTime = DateTime.Now,
                EditUserId = _currentUser.UserId
            };
            try
            {
                bool result = await sys_MenuHandle.UpdateAsync(Menu);
                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "菜单修改" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "菜单修改失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 删除菜单
        /// </summary>
        /// <param name="menuId"></param>
        /// <returns></returns>
        [HttpGet("DeleteByMenuIdAsync/{menuId}")]
        public async Task<IActionResult> DeleteByMenuIdAsync(string menuId)
        {
            try
            {
                bool result = await sys_MenuHandle.DeleteByIdAsync(menuId);
                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "删除菜单" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "删除菜单失败：" + ex.Message, false));
            }
        }

        /// <summary>
        /// 分页获取所有菜单
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost("GetAllMenuAsync")]
        public async Task<IActionResult> GetAllMenuAsync([FromBody] ApiPageQueryRequest<SysMenu> request)
        {
            try
            {
                var result = await sys_MenuHandle.GetAllAsync((int)request.PageIndex, (int)request.PageSize, ApiPageQueryRequest<SysMenu>.GenerateCondition(request.Condition));
                return Ok(ApiPageQueryResponse<List<SysMenuExtend>>.SetResponse(ApiResponseStatus.Success, "查询成功", (int)request.PageIndex, (int)request.PageSize, result.count, result.menusExt)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiPageQueryResponse<List<SysMenu>>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, (int)request.PageIndex, (int)request.PageSize, 0, new List<SysMenu> { }));
            }
        }

        /// <summary>
        /// 获取菜单树
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetMenuTreeAsync")]
        public async Task<IActionResult> GetMenuTreeAsync()
        {
            try
            {
                var result = await sys_MenuHandle.GetMenuTree();
                return Ok(ApiNormalResponse<List<SysMenuExtend>>.SetResponse(ApiResponseStatus.Success, "查询成功", result)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                // 处理异常情况
                return BadRequest(ApiNormalResponse<List<SysMenu>>.SetResponse(ApiResponseStatus.BadRequest, "查询失败：" + ex.Message, new List<SysMenu> { }));
            }
        }
    }
}